//
//  URL.swift
//  TrustHost
//
//  Created by 好东家 on 2021/5/31.
//

import UIKit
import Photos

extension URL {
    /// 获取本地图片（asset）中的URL
    public static func fromLocalImage(named name: String) -> URL? {
        
        let fileManager = FileManager.default
        let cacheDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
        let url = cacheDirectory.appendingPathComponent("\(name).png")
        let path = url.path
        
        guard fileManager.fileExists(atPath: path) else {
            guard
                let image = UIImage(named: name),
                let data = image.pngData()
                else { return nil }
            /// 通过写入图片数据实现 路径url
            fileManager.createFile(atPath: path, contents: data, attributes: nil)
            return url
        }
        return url
    }
    
    
    // MARK: - 视频
    
    ///获取视频第一帧的图片
    public func getVideoPreViewImage() ->UIImage{
        
        let asset =  AVURLAsset.init(url: self)
        
        let gen = AVAssetImageGenerator.init(asset: asset)
        
        gen.appliesPreferredTrackTransform = true
        
        let time = CMTimeMakeWithSeconds(0.0, preferredTimescale: 600)
        
        var actualTime = CMTimeMake(value: 0, timescale: 0)
        
        do{
            let image = try gen.copyCGImage(at: time, actualTime: &actualTime)
            
            return UIImage.init(cgImage: image)
            
        }catch let err as NSError{
            print("出现错误!\(err)")
        }
        
        return UIImage.init()
    }

    
    
    
}
